<template>
  <div class="trade-market-container">
    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索商品" 
            clearable 
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-select 
            v-model="selectedCategory" 
            placeholder="选择分类" 
            clearable
            @change="handleFilter"
          >
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-select 
            v-model="selectedSort" 
            placeholder="排序方式" 
            clearable
            @change="handleFilter"
          >
            <el-option label="按价格升序" value="price_asc" />
            <el-option label="按价格降序" value="price_desc" />
            <el-option label="按发布时间降序" value="time_desc" />
            <el-option label="按热度降序" value="popular_desc" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6">
          <el-button-group>
            <el-button type="primary" @click="handleFilter" :icon="Search">筛选</el-button>
            <el-button @click="resetFilter" :icon="Refresh">重置</el-button>
          </el-button-group>
        </el-col>
      </el-row>
      
      <!-- 扩展筛选条件 -->
      <div class="advanced-filters" v-if="showAdvancedFilters">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-slider 
              v-model="priceRange" 
              range 
              :min="0" 
              :max="5000" 
              :step="50" 
              show-stops
              @change="handleFilter"
            >
              <template #prefix>价格区间:</template>
            </el-slider>
          </el-col>
          <el-col :span="6">
            <el-checkbox-group v-model="selectedStatus" @change="handleFilter">
              <el-checkbox label="1">在售</el-checkbox>
              <el-checkbox label="2">已售</el-checkbox>
              <el-checkbox label="3">预售</el-checkbox>
            </el-checkbox-group>
          </el-col>
          <el-col :span="6">
            <el-checkbox-group v-model="selectedTags" @change="handleFilter">
              <el-checkbox label="new">新品</el-checkbox>
              <el-checkbox label="discount">折扣</el-checkbox>
              <el-checkbox label="urgent">急售</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-row>
      </div>
      
      <div class="filter-toggle">
        <el-link type="primary" @click="toggleAdvancedFilters">
          {{ showAdvancedFilters ? '收起高级筛选' : '展开高级筛选' }}
          <el-icon :class="{ 'rotate-icon': showAdvancedFilters }">
            <ArrowDown />
          </el-icon>
        </el-link>
      </div>
    </div>

    <!-- 商品列表区域 -->
    <div class="product-list-container">
      <el-empty 
        v-if="filteredProducts.length === 0" 
        description="暂无符合条件的商品" 
        :image-size="200"
      >
        <el-button type="primary" @click="resetFilter">重置筛选条件</el-button>
      </el-empty>
      
      <el-card 
        v-for="product in filteredProducts" 
        :key="product.id" 
        class="product-card" 
        shadow="hover"
        :body-style="{ padding: '0' }"
      >
        <div class="product-img-container">
          <el-image 
            :src="product.coverImage" 
            class="product-img" 
            fit="cover" 
            lazy
            :preview-src-list="[product.coverImage]"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>
          
          <div class="product-tags">
            <el-tag v-if="product.isNew" type="danger" effect="dark" size="small">新品</el-tag>
            <el-tag v-if="product.discount" type="success" effect="dark" size="small">
              折扣 {{ Math.round((1 - product.price/product.originalPrice)*100) }}%
            </el-tag>
            <el-tag v-if="product.urgent" type="warning" effect="dark" size="small">急售</el-tag>
          </div>
          
          <div class="product-status" :class="{
            'status-available': product.status === 1,
            'status-sold': product.status === 2,
            'status-reserved': product.status === 3
          }">
            {{ getStatusText(product.status) }}
          </div>
        </div>
        
        <div class="product-info">
          <div class="product-name" :title="product.name">{{ product.name }}</div>
          
          <div class="product-price">
            <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
            <span class="original-price" v-if="product.originalPrice">
              ¥{{ product.originalPrice.toFixed(2) }}
            </span>
          </div>
          
          <div class="product-meta">
            <div class="meta-item">
              <el-icon><Location /></el-icon>
              <span>{{ product.location }}</span>
            </div>
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>{{ product.sellerName }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(product.createTime) }}</span>
            </div>
          </div>
          
          <div class="product-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click.stop="goProductDetail(product.id)"
            >
              查看详情
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click.stop="addToFavorites(product.id)"
              :icon="product.isFavorited ? StarFilled : Star"
            >
              {{ product.likes }}
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="filteredProducts.length > 0">
  <el-pagination
    v-model:current-page="currentPage"
    :page-size="pageSize"
    :total="totalFilteredProducts"
    :page-sizes="[10, 20, 30, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handlePageChange"
  />
</div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { 
  Search, Refresh, ArrowDown, Location, 
  User, Clock, Star, StarFilled, Picture 
} from '@element-plus/icons-vue';

// 直接在组件内定义模拟商品数据
const mockProducts = [
  {
    id: 1,
    name: '高等数学教材（全新）',
    price: 25,
    originalPrice: 45,
    coverImage: "https://img0.baidu.com/it/u=3440274094,2161970976&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=703",
    location: 'XX校区',
    likes: 32,
    isNew: true,
    status: 1,
    categoryId: 1,
    createTime: '2025-04-28T10:30:00',
    description: '全新高等数学教材，未使用过',
    tags: ['教材', '数学'],
    sellerName: '张同学',
    isFavorited: false,
    discount: true,
    urgent: false
  },
  {
    id: 2,
    name: '二手笔记本电脑',
    price: 1200,
    originalPrice: 2500,
    coverImage: "https://img0.baidu.com/it/u=3429702705,3684248660&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=667",
    location: 'XX校区',
    likes: 45,
    status: 1,
    categoryId: 2,
    createTime: '2025-04-27T16:45:00',
    description: '九成新笔记本电脑，配置良好',
    tags: ['电子', '电脑'],
    sellerName: '李同学',
    isFavorited: true,
    discount: true,
    urgent: true
  },
  // 更多模拟数据...
  {
    id: 3,
    name: '自行车 9成新',
    price: 150,
    originalPrice: 300,
    coverImage: "https://img0.baidu.com/it/u=3796084184,31735756&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
    location: 'XX校区',
    likes: 28,
    status: 1,
    categoryId: 5,
    createTime: '2025-04-26T14:20:00',
    description: '轻便自行车，适合校园骑行',
    tags: ['运动', '交通'],
    sellerName: '王同学',
    isFavorited: false,
    discount: true,
    urgent: false
  },
  {
    id: 4,
    name: '考研英语复习资料',
    price: 15,
    originalPrice: 30,
    coverImage: "https://img2.baidu.com/it/u=4013093803,3551903531&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666",
    location: 'XX校区',
    likes: 19,
    status: 2,
    categoryId: 1,
    createTime: '2025-04-25T11:15:00',
    description: '全套考研英语资料，含历年真题',
    tags: ['教材', '考研'],
    sellerName: '赵同学',
    isFavorited: false,
    discount: true,
    urgent: false
  },
  {
    id: 5,
    name: '耳机 音质良好',
    price: 50,
    originalPrice: 120,
    coverImage: "https://img1.baidu.com/it/u=2332961593,3611488811&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666",
    location: 'XX校区',
    likes: 36,
    isNew: true,
    status: 1,
    categoryId: 2,
    createTime: '2025-04-24T09:30:00',
    description: '高品质耳机，音质清晰',
    tags: ['电子', '耳机'],
    sellerName: '钱同学',
    isFavorited: true,
    discount: true,
    urgent: true
  },
  {
    id: 6,
    name: '台灯 可调节亮度',
    price: 20,
    originalPrice: 40,
    coverImage: "https://img0.baidu.com/it/u=1680341359,4041575327&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    location: 'XX校区',
    likes: 22,
    status: 1,
    categoryId: 4,
    createTime: '2025-04-23T18:45:00',
    description: '护眼台灯，多档亮度调节',
    tags: ['生活', '电器'],
    sellerName: '孙同学',
    isFavorited: false,
    discount: true,
    urgent: false
  },
  {
    id: 7,
    name: 'Java编程思想',
    price: 30,
    originalPrice: 60,
    coverImage: "https://t15.baidu.com/it/u=3085488172,2160534927&fm=224&app=112&f=JPEG?w=500&h=500",
    location: 'XX校区',
    likes: 41,
    status: 1,
    categoryId: 1,
    createTime: '2025-04-22T16:20:00',
    description: '经典编程书籍，适合Java学习者',
    tags: ['教材', '编程'],
    sellerName: '周同学',
    isFavorited: true,
    discount: true,
    urgent: false
  },
  {
    id: 8,
    name: '篮球 7成新',
    price: 40,
    originalPrice: 80,
    coverImage: "https://img0.baidu.com/it/u=1315648068,2940794644&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=667",
    location: 'XX校区',
    likes: 15,
    status: 1,
    categoryId: 5,
    createTime: '2025-04-21T14:10:00',
    description: '标准篮球，适合日常锻炼',
    tags: ['运动', '篮球'],
    sellerName: '吴同学',
    isFavorited: false,
    discount: true,
    urgent: true
  }
];

// 商品数据
const products = ref([]);

// 获取商品数据 - 现在直接从本地mock数据获取
const fetchProducts = async () => {
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    products.value = mockProducts;
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
};

onMounted(() => {
  fetchProducts();
});
// 模拟商品分类数据
const categories = ref([
  { id: 1, name: '教材书籍' },
  { id: 2, name: '电子数码' },
  { id: 3, name: '服饰鞋包' },
  { id: 4, name: '生活用品' },
  { id: 5, name: '运动户外' },
  { id: 6, name: '美妆个护' },
  { id: 7, name: '家具家电' },
  { id: 8, name: '其他类别' }
]);

// 筛选条件
const searchKeyword = ref('');
const selectedCategory = ref(null);
const selectedSort = ref(null);
const priceRange = ref([0, 5000]);
const selectedStatus = ref(['1']); // 默认只显示在售商品
const selectedTags = ref([]);
const showAdvancedFilters = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(12);

// 格式化时间
const formatTime = (timeString) => {
  const now = new Date();
  const time = new Date(timeString);
  const diffHours = Math.floor((now - time) / (1000 * 60 * 60));
  
  if (diffHours < 1) {
    return '刚刚';
  } else if (diffHours < 24) {
    return `${diffHours}小时前`;
  } else {
    return time.toLocaleDateString();
  }
};

// 获取商品状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '在售',
    2: '已售',
    3: '预售'
  };
  return statusMap[status] || '';
};

// 计算属性：根据筛选条件过滤商品列表
const filteredProducts = computed(() => {
  let filtered = [...products.value];

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(product =>
      product.name.toLowerCase().includes(keyword) ||
      (product.description && product.description.toLowerCase().includes(keyword)) ||
      (product.tags && product.tags.some(tag => tag.toLowerCase().includes(keyword)))
)}

  // 分类过滤
  if (selectedCategory.value) {
    filtered = filtered.filter(product => product.categoryId === selectedCategory.value);
  }

  // 价格区间过滤
  filtered = filtered.filter(product => 
    product.price >= priceRange.value[0] && product.price <= priceRange.value[1]
  );

  // 状态过滤
  if (selectedStatus.value.length > 0) {
    filtered = filtered.filter(product => selectedStatus.value.includes(String(product.status)));
  }

  // 标签过滤
  if (selectedTags.value.length > 0) {
    filtered = filtered.filter(product => {
      const productTags = [];
      if (product.isNew) productTags.push('new');
      if (product.discount) productTags.push('discount');
      if (product.urgent) productTags.push('urgent');
      return selectedTags.value.some(tag => productTags.includes(tag));
    });
  }

  // 排序
  if (selectedSort.value === 'price_asc') {
    filtered.sort((a, b) => a.price - b.price);
  } else if (selectedSort.value === 'price_desc') {
    filtered.sort((a, b) => b.price - a.price);
  } else if (selectedSort.value === 'time_desc') {
    filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
  } else if (selectedSort.value === 'popular_desc') {
    filtered.sort((a, b) => b.likes - a.likes);
  }

  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filtered.slice(startIndex, endIndex);
});

// 总商品数量
const totalFilteredProducts = computed(() => {
  // 这里需要重新计算过滤后的总数
  let filtered = [...products.value];
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(product =>
      product.name.toLowerCase().includes(keyword) ||
      (product.description && product.description.toLowerCase().includes(keyword)))
  }
  
  if (selectedCategory.value) {
    filtered = filtered.filter(product => product.categoryId === selectedCategory.value);
  }
  
  filtered = filtered.filter(product => 
    product.price >= priceRange.value[0] && product.price <= priceRange.value[1]
  );
  
  if (selectedStatus.value.length > 0) {
    filtered = filtered.filter(product => selectedStatus.value.includes(String(product.status)));
  }
  
  return filtered.length;
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1;
};

// 重置筛选条件
const resetFilter = () => {
  searchKeyword.value = '';
  selectedCategory.value = null;
  selectedSort.value = null;
  priceRange.value = [0, 5000];
  selectedStatus.value = ['1'];
  selectedTags.value = [];
  currentPage.value = 1;
  handleFilter();
};

// 切换高级筛选
const toggleAdvancedFilters = () => {
  showAdvancedFilters.value = !showAdvancedFilters.value;
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 跳转到商品详情页
const goProductDetail = (id) => {
  // 这里可以实现跳转到具体商品详情页的逻辑，例如使用 vue-router 进行跳转
  console.log(`跳转到商品 ${id} 的详情页`);
};

// 添加到收藏
const addToFavorites = (id) => {
  const product = products.value.find(p => p.id === id);
  if (product) {
    product.isFavorited = !product.isFavorited;
    product.likes += product.isFavorited ? 1 : -1;
  }
};
</script>

<style scoped lang="scss">
.trade-market-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.filter-container {
  margin-bottom: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .el-row {
    margin-bottom: 15px;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
}

.advanced-filters {
  padding: 15px 0;
  border-top: 1px solid #eee;
  margin-top: 15px;
  
  .el-col {
    display: flex;
    align-items: center;
  }
  
  .el-slider {
    width: 100%;
    margin-left: 15px;
  }
  
  .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.filter-toggle {
  text-align: center;
  margin-top: 10px;
  
  .rotate-icon {
    transform: rotate(180deg);
  }
}

.product-list-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
  
  @media (max-width: 480px) {
    grid-template-columns: 1fr;
  }
}

.product-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }
}

.product-img-container {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  
  .product-img {
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease;
  }
  
  &:hover .product-img {
    transform: scale(1.05);
  }
  
  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    color: #999;
    
    .el-icon {
      font-size: 40px;
      margin-bottom: 10px;
    }
  }
}

.product-tags {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  gap: 5px;
}

.product-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
  
  &.status-available {
    background-color: #67c23a;
  }
  
  &.status-sold {
    background-color: #909399;
  }
  
  &.status-reserved {
    background-color: #e6a23c;
  }
}

.product-info {
  padding: 15px;
  
  .product-name {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .product-price {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    
    .current-price {
      color: #ff6600;
      font-size: 20px;
      font-weight: bold;
    }
    
    .original-price {
      color: #999;
      font-size: 14px;
      text-decoration: line-through;
      margin-left: 8px;
    }
  }
  
  .product-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 15px;
    font-size: 13px;
    color: #666;
    
    .meta-item {
      display: flex;
      align-items: center;
      
      .el-icon {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
  
  .product-actions {
    display: flex;
    justify-content: space-between;
    
    .el-button {
      flex: 1;
      margin: 0 5px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>